﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Configuration;
using CCH.Lib;
using System.Web.UI;
using System.Web.UI.WebControls;

/// <summary>
/// SessionCheckModule 的摘要描述
/// </summary>
/// 
namespace CCH.HttpModule
{
    public class SessionCheckModule : IHttpModule
    {

        NLog.Logger logger = NLog.LogManager.GetCurrentClassLogger();



        public SessionCheckModule()
        {

        }

        public void Dispose()
        {
            //throw new NotImplementedException();
        }

        public void Init(HttpApplication context)
        {
            //throw new NotImplementedException();
            context.AcquireRequestState += new EventHandler(Application_AcquireRequestState);

        }

        private void Application_AcquireRequestState(Object source, EventArgs e)
        {
            HttpApplication Application = (HttpApplication)source;

            String url = Application.Context.Request.AppRelativeCurrentExecutionFilePath;


            //TODO:取WebConfig 的略過設定


            //在LIB與PUBLIC內的網頁略過檢查
            if (url.Contains("~/lib"))
            {
                return;
            }
            if (url.Contains("~/public"))
            {
                return;
            }
            if (url.Contains("~/js"))
            {
                return;
            }
            if (url.Contains("~/css"))
            {
                return;
            }


            if (Application.Context.Request.CurrentExecutionFilePathExtension.Equals(".aspx"))
            {
                if (!url.Contains("login"))
                {
                    //true:已登入 false:未登入
                    bool login = Application.Context.Session["UserLogin"] == null ? false : (bool)Application.Context.Session["UserLogin"];

                    if (!login)
                    {
                        //logger.Info("未登入");

                        //取網址LOGIN ResolveUrl

                        String loginUrl = "~/" + System.Web.Configuration.WebConfigurationManager.AppSettings["LoginUrl"];
                        
                        Application.Response.Redirect(loginUrl.ResolveUrl(), false);
                        
                        HttpContext.Current.ApplicationInstance.CompleteRequest();
                    }
                }
            }


        }
    }
}
